<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>demo聊天室</title>
    <link rel="stylesheet" href="css/reset.min.css">
    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="layer/theme/default/layer.css">
    <style>
        .message img {
            float: left;
            width: 40px;
            height: 40px;
            margin-right: 12px;
            border-radius: 50%;
        }

        .you {
            margin-left: 60px;
            margin-top: -39px;
        }

        .me-header {
            float: right !important;
            margin-right: 0 !important;
        }

        .me {
            margin-right: 60px;
            margin-top: -39px;
        }

        .active-chat::-webkit-scrollbar, .left::-webkit-scrollbar {
            width: 2px;
        }
    </style>
</head>
<body>

<div class="wrapper">
    <div class="container">
        <div class="left">
            <div class="top" style="padding: 20px 29px;height: auto;">
                <div class="" style="font: 400 13.3333px Arial;font-weight: 400;">在线人数：<span id="numbers">0</span> 人
                </div>
            </div>
            <ul class="people">
            </ul>
        </div>
        <div class="right">
            <div class="top"><span>Tips: <span class="name">PHP之websocket聊天室</span></span></div>
            <div class="chat active-chat" data-chat="person1"
                 style="height: auto;border-width: 0px;padding: 10px;height: 483px; padding: 10px;overflow-y: auto;scrollTop: 100px">
            </div>
            <div class="write">
                <a href="javascript:;" class="write-link attach"></a>
                <input type="text" id="input-value" onkeydown="confirm(event)"/>
                <a href="javascript:;" class="write-link smiley"></a>
                <a href="javascript:;" class="write-link send" onclick="send()"></a>
            </div>
        </div>
    </div>
</div>

<script src="js/jquery-2.1.1.min.js"></script>
<script src="js/index.js?v=1"></script>
<script src="layer/layer.js"></script>
<script>
    var ws = null;
    var search = window.location.search;
    var token = getSearchString('token', search);
    if (token === undefined) {
        token = '';
    }

    connect();
    function connect() {
        // 创建一个 websocket 连接
        ws = new WebSocket("ws://127.0.0.1:9502?token=" + token);


        // websocket 创建成功事件
        ws.onopen = onopen;
        // websocket 接收到消息事件
        ws.onmessage = onmessage;
        ws.onclose = onclose;
        ws.onerror = onerror;
    }

    function onopen()
    {
        var data = "系统消息：建立连接成功";
        console.log(data);
    }

    function onmessage(e)
    {
        var data = JSON.parse(e.data);

        switch (data.type) {
            case 'handShake':
                console.log(data.msg);
                if (data.hasOwnProperty('user')) {
                    uname = data.user.nickname;
                    headerimg = data.user.head_url;
                    layer.open({
                        title: '您的用户名如下',
                        content: uname,
                        closeBtn: 0,
                        yes: function (index, layero) {
                            layer.close(index);
                        }
                    });
                    //发送用户登录
                    var user_info = {'type': 'login', 'msg': uname, 'headerimg': headerimg};
                    sendMsg(user_info);
                } else {
                    layer.open({
                        title: '提示',
                        content: '用户未登录',
                        closeBtn: 0,
                        yes: function (index, layero) {
                            layer.close(index);
                        }
                    });
                }
                break;
            case 'login':
                userList(data.user_list);
                systemMessage('系统消息: ' + data.msg + ' 已上线');
                break;
            case 'logout':
                userList(data.user_list);
                if (data.msg.length > 0) {
                    systemMessage('系统消息: ' + data.msg + ' 已下线');
                }
                break;
            case 'user':
                messageList(data);
                break;
            case 'system':
                systemMessage();
                break;
        }
    }
    function onclose()
    {
        console.log("连接关闭，定时重连");
        connect();
    }

    // websocket 错误事件
    function onerror()
    {
        var data = "系统消息 : 出错了,请退出重试.";
        console.log(data);
    }

    function confirm(event) {
        var key_num = event.keyCode;
        if (13 == key_num) {
            send();
        } else {
            return false;
        }
    }

    function systemMessage(msg) {
        var html = `<div class="conversation-start">
            <span>` + msg + `</span>
        </div>`;
        var active_chat = document.querySelector('div.active-chat');
        var oldHtml = active_chat.innerHTML;
        active_chat.innerHTML = oldHtml + html;
        active_chat.scrollTop = active_chat.scrollHeight;
    }

    function send() {
        var msg = document.querySelector("input#input-value").value;
        var reg = new RegExp("\r\n", "g");
        msg = msg.replace(reg, "");
        sendMsg({type: "user", msg: msg, from: uname, headerimg: headerimg});
        document.querySelector("input#input-value").value = "";
    }

    function sendMsg(msg) {
        var data = JSON.stringify(msg);
        ws.send(data);
    }

    function userList(user) {
        var html = '';
        var number = 0;
        console.log(user);
        for (var i = 0; i < user.length; i++) {
            html += `<li class="person" data-chat="person1">
                    <img src="img/` + user[i].headerimg + `" alt=""/>
                    <span class="name">` + user[i].username + `</span>
                    <span class="time">` + user[i].login_time + `</span>
                    <span class="preview" style="color: green;font-size: 7px;">` + user[i].status + `</span>
                </li>`;
            if (user[i].status === '在线') {
                number++;
            }
        }
        document.querySelector('ul.people').innerHTML = html;
        //document.querySelector('span#numbers').innerHTML = user.length;
        document.querySelector('span#numbers').innerHTML = number;
    }

    function messageList(data) {
        console.log(data);
        if (data.from == uname) {
            var html = `<div class="message">
                    <img class="me-header" src="img/` + data.headerimg + `" alt=""/>
                    <div class="bubble me">` + data.msg + `</div>
                </div>`;
        } else {
            var html = `<div class="message">
                    <img src="img/` + data.headerimg + `" alt=""/>
                    <div class="bubble you">` + data.msg + `</div>
                </div>`;
        }
        var active_chat = document.querySelector('div.active-chat');
        var oldHtml = active_chat.innerHTML;
        active_chat.innerHTML = oldHtml + html;
        active_chat.scrollTop = active_chat.scrollHeight;
    }

    function getSearchString(key, Url) {
        var str = Url;
        str = str.substring(1, str.length); // 获取URL中?之后的字符（去掉第一位的问号）
        // 以&分隔字符串，获得类似name=xiaoli这样的元素数组
        var arr = str.split("&");
        var obj = new Object();
        // 将每一个数组元素以=分隔并赋给obj对象
        for (var i = 0; i < arr.length; i++) {
            var tmp_arr = arr[i].split("=");
            obj[decodeURIComponent(tmp_arr[0])] = decodeURIComponent(tmp_arr[1]);
        }
        return obj[key];
    }
</script>
</body>
</html>
